package com.eonmind.vip.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.eonmind.common.contract.timer.Timer;
import com.eonmind.common.provider.entity.vip.VipPackage;
import com.eonmind.common.provider.entity.vip.Subscription;
import com.eonmind.common.provider.entity.vip.UserWelfare;
import com.eonmind.common.provider.dto.VipDto;
import com.eonmind.vip.mapper.VipPackageMapper;
import com.eonmind.vip.mapper.SubscriptionMapper;
import com.eonmind.vip.mapper.UserWelfareMapper;
import com.eonmind.vip.provider.VipToUserServerProvider;
import com.eonmind.vip.service.VipToPayService;
import com.eonmind.vip.util.TimeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class VipToPayServiceImpl implements VipToPayService {

    @Autowired
    private SubscriptionMapper subscriptionMapper;

    @Autowired
    private VipPackageMapper vipPackageMapper;

    @Autowired
    private UserWelfareMapper userWelfareMapper;

    @Autowired
    private VipToUserServerProvider vipToUserServerProvider;


    @Override
    public Boolean updateUserPlan(List<VipDto.PayToVipOrderSucDto> list) {
        // 为空返回false
        if (ObjectUtil.isEmpty(list)) {
            return false;
        }
        updateSales(list);
        // 获取用户ID
        Long userId = list.get(0).getUserId();
        // 提取套餐的ids
        List<Long> ids = list.stream().map(VipDto.PayToVipOrderSucDto::getPlanId).toList();
        // 查询用户当前个人权益
        UserWelfare userWelfare = userWelfareMapper.getUserPlanByUserID(userId);
        if (ObjectUtil.isEmpty(userWelfare)) {
            vipToUserServerProvider.initUserWelfare(userId);
            userWelfare = userWelfareMapper.getUserPlanByUserID(userId);
        }
        HashMap<Long, VipPackage> packageHashMap = new HashMap<>();

        for (VipPackage vipPackage: vipPackageMapper.getPlanByIds(ids)) {
            packageHashMap.put(vipPackage.getId(), vipPackage);
        }

        int aiDrawTime = 0, aiVideoTime = 0;
        for (VipDto.PayToVipOrderSucDto item: list) {
            Long planId = item.getPlanId();
            aiDrawTime = packageHashMap.get(planId).getAiDraw() * item.getNum();
            aiVideoTime = packageHashMap.get(planId).getAiVideo() * item.getNum();
        }

        // 根据用户Id以及激活状态返回用户当前生效的订阅记录
        List<Subscription> subscriptionList = subscriptionMapper.getActSubByPlanId$UserId(ids, userId, "active");
        // 过滤用户本次购买的套餐与有效订阅记录中相同的，并延长其截止时间
        subscriptionList.forEach(item -> {
            list.stream()
                    .filter(item2 -> item.getPlanId().equals(item2.getPlanId()))
                    .findFirst()
                    .ifPresent(item2 -> item.setEndDate(TimeUtil.timeMinusMillis(item2.getNum() * packageHashMap.get(item2.getPlanId()).getDuration(), item.getEndDate())));
        });
        HashSet<Object> objects = new HashSet<>();

        // 获取用户权益中的所有生效的套餐id, 并移除与list中重复的部分
        List<Long> activeSubscriptionIds = userWelfare.getActiveSubscriptionIds();
        HashSet<Long> existIds = new HashSet<>(activeSubscriptionIds);
        list.removeIf(payPlanDto ->
                payPlanDto != null &&
                        payPlanDto.getPlanId() != null &&
                        existIds.contains(payPlanDto.getPlanId())
        );
        // 生成新增的套餐ids,并建立出一个订阅列表
        List<Long> newPlanIds = list.stream().map(VipDto.PayToVipOrderSucDto::getPlanId).toList();
        for (VipDto.PayToVipOrderSucDto payPlanDto: list) {
            Subscription subscription = new Subscription();
            BeanUtil.copyProperties(payPlanDto, subscription);
            subscription.setEndDate(TimeUtil.timeMinusMillis(payPlanDto.getNum() * packageHashMap.get(payPlanDto.getPlanId()).getDuration(), Timer.currentTimestamp()))
                    .setStartDate(Timer.currentTimestamp())
                    .setCoinsEarned(0)
                    .setLastCoinDate(Timer.currentTimestamp())
                    .setStatus("active")
                    .setCreateTime(Timer.currentTimestamp())
                    .setUpdateTime(Timer.currentTimestamp());
            subscriptionList.add(subscription);
        }
        // 更新用户的生效套餐ids
        updateUserPlanSubList(newPlanIds, userId);
        // 根据生效套餐ids, 更新用户权益
        updateUserWelfareByActive(userId, aiDrawTime, aiVideoTime);
        // 更新用户总积分
        updateUserTotalPoints(newPlanIds, userId);
        // 更新用户订阅记录
        subscriptionMapper.saveAllSub(subscriptionList);
        return null;
    }

    @Override
    public List<VipPackage> getAllPackages() {
        return vipPackageMapper.list();
    }

    /**
      * @Author 逆飞的流星
      * @Description 更新用户订阅信息
      * @Date 20:19 2025/5/21
      **/


    /**
      * @Author 逆飞的流星
      * @Description 保存订阅信息
      * @Date 20:33 2025/5/21
      **/
    private void saveSubscriptions(List<VipDto.PayToVipOrderSucDto> list){

    }

    /**
      * @Author 逆飞的流星
      * @Description
      * @Date 20:38 2025/5/21
      **/
    private void updateUserPlanSubList(List<Long> planIds, Long userId) {
        UserWelfare userWelfare = userWelfareMapper.getUserPlanByUserID(userId);
        if (ObjectUtil.isEmpty(userWelfare)) {
            throw new IllegalArgumentException("用户不存在");
        }
        List<Long> activeIds = Optional.ofNullable(userWelfare.getActiveSubscriptionIds())
                .orElseGet(ArrayList::new);
        activeIds.addAll(planIds);
        userWelfare.setActiveSubscriptionIds(activeIds);
        List<Long> historyIds = Optional.ofNullable(userWelfare.getSubscriptionHistoryIds())
                .orElseGet(ArrayList::new);
        userWelfare.setSubscriptionHistoryIds(historyIds);
        userWelfareMapper.updateUserPlanByUserID(userId, userWelfare);
    }

    /**
      * @Author 逆飞的流星
      * @Description 根据active列表更新用户权益
      * @Date 23:02 2025/5/21
      **/
    public void updateUserWelfareByActive(Long userId, int newDrawTime, int newVideoTime) {
        UserWelfare userWelfare = userWelfareMapper.getUserPlanByUserID(userId);
        List<Long> activePlanList = userWelfare.getActiveSubscriptionIds();
        List<VipPackage> vipPackages = vipPackageMapper.getPlanByIds(activePlanList);
        int dailyPoints = 0;
        for (VipPackage vipPackage : vipPackages) {
            dailyPoints += vipPackage.getDailyCoins();
        }
        UserWelfare.CachedFeatures.Features features1 = userWelfare.getCachedFeatures().getFeatures();
        newVideoTime = features1.getVideo() + newVideoTime;
        newDrawTime = features1.getDrawing() + newDrawTime;

        UserWelfare.CachedFeatures.Features features = new UserWelfare.CachedFeatures.Features()
                .setVideo(newVideoTime).setDrawing(newDrawTime);

        UserWelfare.CachedFeatures cachedFeatures = new UserWelfare.CachedFeatures()
                .setDailyCoins(dailyPoints)
                .setFeatures(features);
        UserWelfare userWelfare1 = new UserWelfare()
                .setUpdateTime(Timer.currentTimestamp())
                .setUserId(userWelfare.getUserId())
                .setCachedFeatures(cachedFeatures);
        Boolean res = userWelfareMapper.updateUserPlanByUserID(userId, userWelfare1);
    }

    /**
      * @Author 逆飞的流星
      * @Description 更新用户当前获得的总积分数量
      * @Date 23:13 2025/5/21
      **/
    public void updateUserTotalPoints(List<Long> newPlanIds, Long userId) {
        int addPoints = 0;
        for (VipPackage vipPackage : vipPackageMapper.getPlanByIds(newPlanIds)) {
            addPoints += vipPackage.getDailyCoins();
        }
        userWelfareMapper.updateTotalPoints(userId, addPoints);
    }

    public void updateSales(List<VipDto.PayToVipOrderSucDto> list) {
        list.forEach(item -> {
            vipPackageMapper.updateSales(item.getPlanId(), item.getNum());
        });
    }
}
